package com.heima.user.gateway.filter;

import com.heima.user.gateway.util.AppJwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.internal.util.logging.Log_$logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

@Component
@Order(-1)
@Slf4j
@RefreshScope //热更新  实现配置的动态刷新功能
public class AuthFilter implements GlobalFilter
{
    @Value("${ignoreUrl}") //主要用于将外部配置的值注入到 Bean 的属性中  从配置文件中读取 ignoreUrl 的值
    private List<String> ignoreUrl;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        log.info("过滤器执行");
        //解析token，看下过期没有
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        //判断是否为登录请求
        String path = request.getURI().getPath();
        if(ignoreUrl.contains(path)){
            log.info("登录请求，请放行");
           return  chain.filter(exchange);
        }
        //获取token
        String token = request.getHeaders().getFirst("token");
        if(StringUtils.isEmpty(token)){
            log.info("token为空，无法继续执行");
                response.setStatusCode(HttpStatus.UNAUTHORIZED);
                return response.setComplete();
        }
        Claims claims = AppJwtUtil.getClaimsBody(token);
        int flag = AppJwtUtil.verifyToken(claims);
        if(flag==1||flag==2){
            log.info("token过期");
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        /**
         * 将当前的请求 / 响应对象（exchange）传递给过滤器链中的下一个过滤器进行处理
         */
        return chain.filter(exchange);
    }
}
